package cn.daniellee.plugin.pm.listener;

import cn.daniellee.plugin.pm.PartnerMission;
import cn.daniellee.plugin.pm.component.ItemGenerator;
import cn.daniellee.plugin.pm.core.MissionCore;
import cn.daniellee.plugin.pm.menu.MenuCommon;
import cn.daniellee.plugin.pm.menu.MissionMenu;
import cn.daniellee.plugin.pm.menu.PlayerMenu;
import cn.daniellee.plugin.pm.menu.InviteMenu;
import cn.daniellee.plugin.pm.model.Mission;
import cn.daniellee.plugin.pm.model.PlayerData;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.*;
import org.bukkit.inventory.Inventory;

import java.util.*;

public class MenuListener implements Listener {

	/**
	 * 处理菜单的点击事件
	 * @param e 事件
	 */
	@EventHandler
	public void onInventoryClick(InventoryClickEvent e) {
		Inventory menu = e.getInventory();
		if (menu != null && menu.getHolder() != null) {
			if (menu.getHolder() instanceof MissionMenu.MissionMenuHolder) {
				e.setCancelled(true);
				Player player = (Player) e.getWhoClicked();
				if (e.getCurrentItem() == null || e.getCurrentItem().getItemMeta() == null) return;
				// 获取任务信息
				Mission mission = MissionCore.getPlayerActiveMission(player.getName());
				// 点击自己头像
				if (e.getRawSlot() == 11) player.openInventory(PlayerMenu.generate(player));
				else if (e.getRawSlot() == 15) { // 点击伙伴或邀请列表
					if (mission == null) player.openInventory(InviteMenu.generate(player));
					else {
						Player partner = Bukkit.getPlayer(mission.getInviter().equals(player.getName()) ? mission.getInvitee() : mission.getInviter());
						if (partner != null) player.teleport(partner);
						else player.sendMessage((PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.partner-offline", "&ePartner is not currently online.")).replace("&", "§"));
					}
				} else if (e.getRawSlot() >= 27) {
					String itemName = e.getCurrentItem().getItemMeta().getDisplayName();
					if (mission == null) { // 未在执行任务，打开的是邀请列表
						PlayerData playerData = PartnerMission.getInstance().getStorage().getPlayerByName(player.getName());
						if (e.getRawSlot() == 45) { // 上一页
							player.openInventory(MissionMenu.generate(player, playerData.isByTimes(), playerData.isShowOffline(), Integer.parseInt(MenuCommon.parseVariable(itemName, PartnerMission.getInstance().getConfig().getString("menu.common.back.name", "&eBack to {page}"), "{page}"))));
						} else if (e.getRawSlot() == 53) { // 下一页
							player.openInventory(MissionMenu.generate(player, playerData.isByTimes(), playerData.isShowOffline(), Integer.parseInt(MenuCommon.parseVariable(itemName, PartnerMission.getInstance().getConfig().getString("menu.common.next.name", "&eNext to {page}"), "{page}"))));
						} else if (e.getRawSlot() == 48) { // 排序
							playerData.setByTimes(!playerData.isByTimes());
							Map<String, Object> fields = new HashMap<>();
							fields.put("by_times", playerData.isByTimes());
							PartnerMission.getInstance().getStorage().updatePlayer(player.getName(), fields);
							player.openInventory(MissionMenu.generate(player, playerData.isByTimes(), playerData.isShowOffline(), 1));
						} else if (e.getRawSlot() == 50) { // 筛选
							playerData.setShowOffline(!playerData.isShowOffline());
							Map<String, Object> fields = new HashMap<>();
							fields.put("show_offline", playerData.isShowOffline());
							PartnerMission.getInstance().getStorage().updatePlayer(player.getName(), fields);
							player.openInventory(MissionMenu.generate(player, playerData.isByTimes(), playerData.isShowOffline(), 1));
						} else if (e.getRawSlot() < 45) { // 玩家
							Player invitee = Bukkit.getPlayer(MenuCommon.parseVariable(itemName, PartnerMission.getInstance().getConfig().getString("menu.mission.button.player.name", "&a&lPlayer: &b&l{player}"), "{player}"));
							MissionCore.invitePlayer(player, invitee);
						}
					} else { // 执行任务中，打开的是任务信息
						if (e.getRawSlot() == 49) { // 领取奖励
							if (mission.getProgress() == 5) {
								if (mission.getInviter().equals(player.getName()) && !mission.isInviterReward()) {
									MissionCore.sendReword(player, mission);
									if (mission.isInviteeReward()) MissionCore.missions.remove(mission);
									else mission.setInviterReward(true);
								} else if (mission.getInvitee().equals(player.getName()) && !mission.isInviteeReward()) {
									MissionCore.sendReword(player, mission);
									if (mission.isInviterReward()) MissionCore.missions.remove(mission);
									else mission.setInviteeReward(true);
								}
								PlayerData playerData = PartnerMission.getInstance().getStorage().getPlayerByName(player.getName());
								player.openInventory(MissionMenu.generate(player, playerData.isByTimes(), playerData.isShowOffline(), 1));
							} else player.sendMessage((PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.cant-claim", "&eThe task has not been completed, the reward cannot be claimed.")).replace("&", "§"));
						}
					}
				}
			} else if (menu.getHolder() instanceof InviteMenu.InviteMenuHolder) {
				e.setCancelled(true);
				Player player = (Player) e.getWhoClicked();
				if (e.getCurrentItem() == null || e.getCurrentItem().getItemMeta() == null) return;
				String itemName = e.getCurrentItem().getItemMeta().getDisplayName();
				Player inviter = Bukkit.getPlayer(MenuCommon.parseVariable(itemName, PartnerMission.getInstance().getConfig().getString("menu.invite.button.player.name", "&a&lPlayer: &b&l{player}"), "{player}"));
				MissionCore.beginMission(inviter, player);
			} else if (menu.getHolder() instanceof PlayerMenu.PlayerMenuHolder) {
				e.setCancelled(true);
				// 防止取出物品
				if (e.isShiftClick()) return;
				Player player = (Player) e.getWhoClicked();
				if (e.getCurrentItem() == null || e.getCurrentItem().getItemMeta() == null) return;
				PlayerData playerData = PartnerMission.getInstance().getStorage().getPlayerByName(player.getName());
				if (e.getRawSlot() == 0) {
					playerData.setEnabled(!playerData.isEnabled());
					if (playerData.isEnabled()) menu.setItem(0, ItemGenerator.getItem(PartnerMission.getInstance().getConfig().getString("menu.edit.button.enable.name", "&a&lNeed partner"), PartnerMission.getInstance().getConfig().getStringList("menu.edit.button.enable.lore"), PartnerMission.getInstance().getConfig().getString("menu.edit.button.enable.item.material", "BEACON"), PartnerMission.getInstance().getConfig().getInt("menu.edit.button.enable.item.durability", 0)));
					else menu.setItem(0, ItemGenerator.getItem(PartnerMission.getInstance().getConfig().getString("menu.edit.button.disable.name", "&a&lNeed partner"), PartnerMission.getInstance().getConfig().getStringList("menu.edit.button.disable.lore"), PartnerMission.getInstance().getConfig().getString("menu.edit.button.disable.item.material", "TNT"), PartnerMission.getInstance().getConfig().getInt("menu.edit.button.disable.item.durability", 0)));
					Map<String, Object> fields = new HashMap<>();
					fields.put("enabled", playerData.isEnabled());
					PartnerMission.getInstance().getStorage().updatePlayer(player.getName(), fields);
					player.sendMessage((PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.switch-success", "&eStatus modified successfully.")).replace("&", "§"));
				} else if (e.getRawSlot() == 2) {
					player.closeInventory();
					MissionCore.editOperation.put(player.getName(), playerData.getContact());
					player.sendMessage((PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.edit-contact", "&ePlease send your contact information, send cancel to quit.")).replace("&", "§"));
				} else if (e.getRawSlot() == 4) {
					player.closeInventory();
					MissionCore.editOperation.put(player.getName(), new ArrayList<>(playerData.getIntroduction()));
					player.sendMessage((PartnerMission.getInstance().getPrefix() + PartnerMission.getInstance().getConfig().getString("message.edit-intro", "&eEnter the introduction edit mode, send &badd [content] &eto add a line, send &bset [line] [content] &eto modify a line, send &bdel [line] &eto delete a line, send &bok &eto complete, the current introduction is:")).replace("&", "§"));
					List<String> introduction = playerData.getIntroduction();
					for (int i = 0; i < introduction.size(); i++) player.sendMessage(("&e" + (i + 1) + ". &r" + introduction.get(i)).replace("&", "§"));
				}
			}
		}
	}
}
